<?php
 /**
  * 导入历史请假记录
  * **/
apf_require_class('Oa_Job_Attendance_Abstract');
apf_require_class("Tools_Tools");

class Oa_Job_Attendance_ImportHistoryLeaveData extends Oa_Job_Attendance_Abstract {

    /** 数据库读 **/
    private $readdb = 'attendance_slave';

    /** 数据库写 **/
    private $writedb = 'attendance_master';

    private $ibook_readdb = 'ibook_slave';

    /** 历史假记录 **/
    private $file = 'have_used.csv';

    /** 分公司2012年数据 **/
    private $sub_company_annual = 'not_shanghai_annual.csv';
    /**
     * 线上环境运行时
     * 1 先执行请假记录数据迁移
     * 2 计算历史年假
     *
     * @param mixed $params
     * @access public
     * @return void
     */
    public function run($params) {
        $this->log("开始执行啦！");
        if($params['type'] == 'history') {
            $this->history_to_history_annual();
        } elseif($params['type'] == 'leave_stat') {//迁移，第一步，其他无关系
            $this->import_laeve_stat_data();
        } elseif ($params['type'] == 'department') {
            $this->get_old_Home_data_department();
        } elseif ($params['type'] == 'home') {
            $this->get_old_home_data();
        } elseif ($params['type'] == 'used_annual') {//年假清0
            $this->import_history_used_annual('2010-12-31 00:00:00');
        } elseif ($params['type'] == '2009') {
            $this->import_history_used_annual_nine('2009-12-31 00:00:00');
        } elseif ($params['type'] == '2009file') {
            $this->import_history_used_annual_nine_file('2009-12-31 00:00:00');
        } elseif ($params['type'] == 'countgc') {
            $this->convert_gongchu_leave_time($params['time']);
        }
        elseif($params['type'] == 'init_table'){
            $this->init_apps();
            $this->init_admin_role();
            $this->log('数据导入成功...');
        }else {
            $this->log('请输入参数');
        }
        $this->log("Job 执行完成！");
    }

    //初始化表apps
    private function init_apps(){
       $sql = "REPLACE INTO `apps` VALUES (?,?,?)";
       $this->execute($sql,array('1', '我的考勤', '/'),$this->writedb);
       $this->execute($sql,array('2', '请假', '/askleave/'),$this->writedb);
       $this->execute($sql,array('3', '出差', '/trip/'),$this->writedb);
       $this->execute($sql,array('4', '公出', '/corptrip/'),$this->writedb);
       $this->execute($sql,array('5', '审批', '/audit/'),$this->writedb);
       $this->execute($sql,array('6', '考勤报告', '/report/'),$this->writedb);
       $this->execute($sql,array('7', '权限管理', '/manage/'),$this->writedb);
    }
    //初始化表 admin_role
    private function init_admin_role(){
        $sql = "REPLACE INTO `admin_role` VALUES (?,?,?);";
        $this->execute($sql,array('5', '普通员工', '1,2,3,4'),$this->writedb);
        $this->execute($sql,array('4', '销售人员', '1,2,3'),$this->writedb);
        $this->execute($sql,array('3', 'HR', '1,2,3,4,5,6'),$this->writedb);
        $this->execute($sql,array('2', 'Bos', '1,5,6'),$this->writedb);
        $this->execute($sql,array('1', '管理员', '1,2,3,4,5,6,7'),$this->writedb);
    }

    /**
     * 从ibook.leave_stat 旧考勤系统中导入数据
     * **/
    private function import_laeve_stat_data() {
        /** 组装常有数据 **/
        $q_sql = "SELECT user_id,code,kd_em_id FROM user_info";
        $d = $this->get_db_rows($q_sql, $this->readdb ,array());
        if($d) {
            foreach ($d as $key => $val) {
                $code[$val['code']] = $val['user_id'];
                $emid[$val['kd_em_id']] = $val['user_id'];
            }
        }
        $start = 0;
        while (true) {
            $sql = "SELECT * FROM leave_stat order by id asc limit $start,100 ";
            $back = $this->get_db_rows($sql, $this->ibook_readdb, array());
            if(empty($back)) {
                break;
            }
            $start += 100;
            foreach ($back as $key => $val) {
                $user_id = $code[$val['Code']];
                /** 获取第一级审批人user_id **/
                $r_user_id = $emid[$val['R_EM_ID']];
                /** 获取第二级审批人user_id **/
                $bemids = explode(',', $val['B_EM_ID']);
                $b_user_id = '';
                if($bemids) {
                    /*
                    foreach ($bemids as $v) {
                        if($v != $val['R_EM_ID']) {
                            $b_user_id = $emid[$v];
                        }
                    }
                    */
                    $r_user_id = $emid[$bemids[0]];
                    if($bemids[1]){
                        $b_user_id = $emid[$bemids[1]];
                    }
                    else{
                        $b_user_id = 0;
                    }
                }
                /** 计算实际天数 **/
                $deal = Tools_Tools::get_instance()->how_many_day($val['start_time'],$val['end_time']);
                $val['leave_long'] = $deal > 0 ? $deal:$val['leave_long'];
                /** 对假期开始,结束时间作处理 把原上下午转为时间点 **/
                if(substr($val['start_time'], 11,6) == '上午') {
                    $val['start_time'] = str_replace('上午', '9:00', $val['start_time']);
                } elseif(substr($val['start_time'], 11,6) == '下午') {
                    $val['start_time'] = str_replace('下午', '14:00', $val['start_time']);
                }

                if(substr($val['end_time'], 11,6) == '上午') {
                    /** 对早上请半天假的情况特殊处理 **/
                    if(substr($val['start_time'], 0,10) == substr($val['end_time'], 0,10)) {
                        $val['end_time'] = str_replace('上午', '14:00', $val['end_time']);
                    } else {
                        $val['end_time'] = str_replace('上午', '9:00', $val['end_time']);
                    }
                } elseif(substr($val['end_time'], 11,6) == '下午') {
                    $val['end_time'] = str_replace('下午', '18:00', $val['end_time']);
                }
                $apply_ext = strtotime($val['apply_time']);

                $i_sql = "INSERT INTO leave_record(user_id,apply_time,apply_time_ext,start_time,end_time,leave_time,type,leave_reason,status,img,r_user_id,b_user_id,is_cancel)
                        VALUE('{$user_id}','{$val['apply_time']}',$apply_ext,'{$val['start_time']}','{$val['end_time']}','{$val['leave_long']}','{$val['leave_type']}','{$val['leave_reason']}','{$val['stat']}','{$val['img']}','{$r_user_id}','{$b_user_id}','{$val['is_cancel']}')";

                $back = $this->execute($i_sql, array(),$this->writedb);
                if($back && $val['trip_date']) {
                    $trip_date = explode(' ', $val['trip_date']);
                    $trip_original = explode(' ', $val['trip_original']);
                    $trip_destingation = explode(' ', $val['trip_destingation']);
                    $trip_method = explode(' ', $val['trip_method']);
                    $trip_hotel = explode(' ', $val['trip_hotel']);
                    $trip_description = explode(' ', $val['trip_description']);
                    if($trip_date) {
                        foreach ($trip_date as $tk => $tv) {
                            if(empty($tv)) {
                                break;
                            }
                            $t_sql = "INSERT INTO trip_detail(leave_id,trip_date,trip_original,trip_destingation,trip_method,trip_hotel,trip_description)
                                      VALUE({$back},'{$tv}','{$trip_original[$tk]}','{$trip_destingation[$tk]}','{$trip_method[$tk]}','{$trip_hotel[$tk]}','{$trip_description[$tk]}')";
                            $back = $this->execute($t_sql, array(),$this->writedb);
                        }
                    }
                }
                if(empty($back)) {
                    $this->log("写入失败".$val['code']);
                }
            }
        }
    }

    /**
     * 从ibook.Home_data 导入部门信息数据
     * */
    private function get_old_Home_data_department() {
        $sql = "SELECT UnitName FROM Home_data group by UnitName order by UnitName desc";
        $result = $this->get_db_rows($sql, $this->ibook_readdb, array());
        foreach ($result  as $val) {
            $val['UnitName'] = trim($val['UnitName']);
            if(empty($val['UnitName']) || strlen($val['UnitName']) < 1) {
                continue;
            }
            $i_sql = "INSERT INTO department(department_name) VALUE('{$val['UnitName']}')";
            $back = $this->execute($i_sql, array(),$this->writedb);
            $s_sql = "INSERT INTO department_manager_map(department_id) VALUE('{$back}')";
            $this->execute($s_sql, array(),$this->writedb);
        }
        $this->log('迁移部门成功');
    }

    /**
     * 从ibook.Home_data 中导入员工基本信息
     * **/
    private function get_old_home_data() {
        $start = 0;
        $q_sql = "SELECT department_id,department_name FROM department";
        $d = $this->get_db_rows($q_sql, $this->readdb ,array());
        if($d) {
            foreach ($d as $key => $val) {
                $department[$val['department_name']] = $val['department_id'];
            }
        }
        while (true) {
            $sql = "SELECT * FROM Home_data order by DimissionTime asc,EnterDate asc limit $start,100 ";
            $back = $this->get_db_rows($sql, $this->ibook_readdb, array());
            if(empty($back)) {
                break;
            }
            $start += 100;
            foreach ($back as $key => $val) {
                $unitname = isset($department['unitname'])? $department['unitname'] : 0;
                $i_sql = "INSERT INTO user_info(name,code,kd_em_id,email,english_name,telphone,mobile,enter_date,dimission_date,position_name,department_id,department_name,group_name,sub_company_name,city_name,service_period,superior_code,employees_type)
                        VALUE('{$val['Name']}','{$val['Code']}','{$val['EM_ID']}','{$val['EMail']}','{$val['FEnglishName']}','{$val['HRMS_UserField_1']}','{$val['Mobile']}','{$val['EnterDate']}','{$val['DimissionTime']}','{$val['Positionname']}','{$unitname}','{$val['UnitName']}','{$val['BusinessGroupName']}','{$val['CompanyName']}','{$val['CompanyName']}','{$val['ServicePeriod']}','{$val['S_Code']}','正式员工')";

                $back = $this->execute($i_sql, array(),$this->writedb);
                if(empty($back)) {
                    $this->log("写入失败".$val['code']);
                }
            }
        }
    }

    /**
     * 导入11～12 年之间的年假 to history_annual
     * */
    public function history_to_history_annual() {
        /** 组装常有数据 **/
        $q_sql = "SELECT user_id,code,kd_em_id FROM user_info";
        $d = $this->get_db_rows($q_sql, $this->readdb ,array());
        if($d) {
            foreach ($d as $key => $val) {
                $code[$val['code']] = $val['user_id'];
            }
        }
        $filepath = realpath(dirname(__FILE__)).'/';
        /** 分公司特殊数据 **/
        if(!file_exists($filepath.$this->sub_company_annual)) {
            $this->log($this->sub_company_annual."文件不存在");
            return '';
        }
        $fp2 = fopen($filepath.$this->sub_company_annual, 'r');
        $sp = array();
        while (!feof($fp2)) {
            $val = fgetcsv($fp2);
            if(empty($val[2]) || empty($val[5])) {
                continue;
            }
            $sp[$val[2]] = $val[5];
        }
        $result = false;
        if(!file_exists($filepath.$this->file)) {
            return $result;
        }
        $have = array();
        $repeat = array();
        $fail = '';
        $fp = fopen($filepath.$this->file, 'r');
        while (!feof($fp)) {
            $val = fgetcsv($fp);
            if(in_array($val[3], $have)) {
                $repeat[] = $val[4];
                continue;
            }
            $used = $val[8] + $val[9];
            if(empty($used) || $used == 0) {
                continue;
            }
            $val[3] = trim($val[3]);
            $have[] = $val[3];
            if(!isset($code[$val[3]])) {
                continue;
            }
            if($val[8]) {
                $data[0] = $code[$val[3]];
                $data[1] = $val[3];
                $data[2] = $val[8];
                $data[3] = '2011';
                $this->insert_history_data($data);
            }
            if($val[9]) {
                //啃人的后来补充数据处理
                if($sp[$val[3]] && $code[$val[3]]) {
                    $subsql = "SELECT sum(leave_time) as leave_long FROM leave_record l where type = '年假' AND (status = '已批准' or status = '未审核') AND user_id = '{$code[$val[3]]}'";
                    $leave = $this->get_db_row($subsql, $this->readdb, array());
                    $leave_day = empty($leave['leave_long']) ? 0:$leave['leave_long'];
                    if($sp[$val[3]] > $leave_day) {
                        $val[9] = $sp[$val[3]] - $leave_day;
                        $this->log("呵呵，给你处理啦!".$leave_day."  Excel数据:".$sp[$val[3]]);
                    }
                    $this->log("处理分公司数据！");
                }
                $data[0] = $code[$val[3]];
                $data[1] = $val[3];
                $data[2] = $val[9];
                $data[3] = '2012';
                $this->insert_history_data($data);
            }
        }
        $this->log("2011，2012年历史数据迁移完成！");
    }

     /**
     * 写入2011，2012年历史数据
     * @param array $data
     * @return int
     * **/
    private function insert_history_data($data){
        $result = '';
        if(empty($data)) {
            return $result;
        }
        $q_sql = "SELECT id FROM history_annual WHERE user_id = {$data[0]} AND year= {$data[3]}";
        $b = $this->get_db_row($q_sql, $this->readdb, array());

        if($b['id']) {
            $r_sql = "UPDATE history_annual SET annual = {$data[2]} WHERE id = {$b['id']}";
            $result = $this->execute($r_sql, array(),$this->writedb);
        } else {
            $e_sql = "INSERT INTO history_annual(user_id,code,annual,year) VALUE({$data[0]},'{$data[1]}','{$data[2]}','{$data[3]}')";
            $result = $this->execute($e_sql, array(),$this->writedb);
        }
        return $result;
    }

    /**
     * 每天更新计算到入职日期的员工年假，清除入职2年以前的年假
     * @param date $end_date
     * */
    public function import_history_used_annual($end_date) {
        /** 组装常有数据 **/
        $q_sql = "SELECT user_id,annual,year FROM history_annual";
        $d = $this->get_db_rows($q_sql, $this->readdb ,array());
        if($d) {
            foreach ($d as $key => $val) {
                //$all[$val['user_id']] += $val['annual'];
                if($val['year'] == '2011') {
                    $all[$val['user_id']][0] = $val['annual'];
                } elseif ($val['year'] == '2012') {
                    $all[$val['user_id']][1] = $val['annual'];
                }
            }
        }
        $start = 0;
        //echo "姓名,员工号,入职时间,总年假,已使用年假,剩余年假,截止2010-12-31年假,2010年入职日到2010-12-31总天数,2010年入职日起年假基数,2010年入职日到2010-12-31年假天数,11年历史使用年假,12年历史使用年假,考勤系统登记年假\n";
        while(true){
            $sql = "SELECT user_id,code,enter_date,name FROM user_info WHERE enter_date != '0000-00-00 00:00:00' AND dimission_date = '0000-00-00 00:00:00' ORDER BY enter_date asc limit $start,100";
            $tmp = $this->get_db_rows($sql, $this->readdb, array());
            if(empty($tmp)) {
                break;
            }
            $start += 100;
            foreach ($tmp as $key => $val) {
                $totalday = 0;
                $enter = strtotime($val['enter_date']);
                $now = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $totalday = intval(ceil(($now - $enter)/86400));
                $year = intval($totalday/365);
                $subsql = "SELECT sum(leave_time) as leave_long FROM leave_record l where type = '年假' AND (status = '已批准' or status = '未审核') AND user_id = '{$val['user_id']}'";
                $leave = $this->get_db_row($subsql, $this->readdb, array());
                $leave_day = empty($leave['leave_long']) ? 0:$leave['leave_long'];
                $enterdate = strtotime($val['enter_date']);
                $now = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $year = intval($totalday/365);
                if($totalday > 365) {
                    $evlevent = 0;
                    $left_annual = 0;
                    $tostop = 0;
                    $twevle = 0;
                    $last_base = 0;
                    $last_days = 0;
                    $work_total = Tools_Tools::get_instance()->clear_annual_to_zero($val['enter_date'],$end_date);
                    if(empty($work_total)) {
                        $history = 0;
                    } else {
                        $history = $work_total['annual'];
                        $tostop = $history;
                        $left_annual = $work_total['left_annual'];
                        $last_base = $work_total['last_base'];
                        $last_days = $work_total['last_day'];
                        $evlevent = isset($all[$val['user_id']]) ? $all[$val['user_id']][0]:0;
                        $twevle = isset($all[$val['user_id']]) ? $all[$val['user_id']][1]:0;
                        $last_year_annual = $work_total['next_annual'];
                        if($left_annual > $evlevent && $evlevent > 0) {
                            //如果2011年修的假少于余下的
                            //$history = $history + ($left_annual - $evlevent);
                        } elseif($left_annual < $evlevent) {
                            //2011年休假超过10年的假，计入12年计算
                            $history += $evlevent - $left_annual;
                        } else {

                        }
                    }
                    if(true) {
                        $update = $history + $leave_day + $twevle;
                        $total_annual = Tools_Tools::get_instance()->annual($val['enter_date']);
                        $update_sql = "REPLACE INTO user_info_ext(user_id,annual_used) VALUE({$val['user_id']},$update)";
                        //echo $update_sql,"+",$history,"+",$leave_day,"+",$excel_annual,"+",$evlevent,"+",$left_annual,"\n";
                        $left = $total_annual - $update;
                        //echo $val['name'],",",$val['code'],",",substr($val['enter_date'],0,10),",",$total_annual,",",$update,",",$left,",",$tostop,",",$last_days,",",$last_base,",",$left_annual,",",$evlevent,",",$twevle,",",$leave_day,"\n";
                        $return = $this->execute($update_sql, array(),$this->writedb);
                        if($return) {
                            echo '更新成功！'."\n";
                        } else {
                            echo '更新失败'."\n";
                            $fail .= $val['Code'].',';
                        }
                    }
                }

            }
        }
    }

    /**
     * 每天更新计算到入职日期的员工年假，2009年12月30日年假
     * @param date $end_date
     * */
    public function import_history_used_annual_nine($end_date) {
        /** 组装常有数据 **/
        $q_sql = "SELECT user_id,annual,year FROM history_annual";
        $d = $this->get_db_rows($q_sql, $this->readdb ,array());
        if($d) {
            foreach ($d as $key => $val) {
                //$all[$val['user_id']] += $val['annual'];
                if($val['year'] == '2011') {
                    $all[$val['user_id']][0] = $val['annual'];
                } elseif ($val['year'] == '2012') {
                    $all[$val['user_id']][1] = $val['annual'];
                }
            }
        }
        $start = 0;
        //echo "姓名,员工号,入职时间,总年假,已使用年假,剩余年假,截止2012-12-31要休年假,截止2010-12-31年假,2010年入职日到2010-12-31总天数,2010年入职日起年假基数,2010年入职日到2010-12-31年假天数,11年历史使用年假,12年历史使用年假,考勤系统登记年假\n";
        while(true){
            $sql = "SELECT user_id,code,enter_date,name FROM user_info WHERE enter_date != '0000-00-00 00:00:00' AND dimission_date = '0000-00-00 00:00:00' ORDER BY enter_date asc limit $start,100";
            $tmp = $this->get_db_rows($sql, $this->readdb, array());
            if(empty($tmp)) {
                break;
            }
            $start += 100;
            foreach ($tmp as $key => $val) {
                $totalday = 0;
                $enter = strtotime($val['enter_date']);
                $now = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $totalday = intval(ceil(($now - $enter)/86400));
                $year = intval($totalday/365);
                $subsql = "SELECT sum(leave_time) as leave_long FROM leave_record l where type = '年假' AND (status = '已批准' or status = '未审核') AND user_id = '{$val['user_id']}'";
                $leave = $this->get_db_row($subsql, $this->readdb, array());
                $leave_day = empty($leave['leave_long']) ? 0:$leave['leave_long'];
                $enterdate = strtotime($val['enter_date']);
                $now = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $year = intval($totalday/365);
                if($totalday > 365) {
                $evlevent = 0;
                    $left_annual = 0;
                    $tostop = 0;
                    $twevle = 0;
                    $last_base = 0;
                    $last_days = 0;
                    $clear_day = 0;
                    $evlevent = isset($all[$val['user_id']]) ? $all[$val['user_id']][0]:0;
                    $work_total = Tools_Tools::get_instance()->clear_annual_to_zero($val['enter_date'],$end_date);
                    $twevle = isset($all[$val['user_id']]) ? $all[$val['user_id']][1]:0;
                    if(empty($work_total)) {
                        $history = 0;
                    } else {
                        $history = $work_total['annual'];
                        $tostop = $history;
                        $left_annual = $work_total['left_annual'];
                        $last_base = $work_total['last_base'];
                        $last_days = $work_total['last_day'];
                        $last_year_annual = $work_total['next_annual'];
                    }
                    apf_require_class('Bll_Attendance_LeaveRecord');
                    $l_bll = new Bll_Attendance_LeaveRecord();
                    $start_day = date('Y-m-d',mktime(0,0,0,1,0,date('Y')));
                    $end_day = date('Y-m-d',mktime(0,0,0,1,0,date('Y')+1));
                    //用户当年请假总数
                    $clear_day = $l_bll->get_annual_by_condition($val['user_id'],$start_day,$end_day);
                    //推算需要清零的假
                    $sys = Tools_Tools::get_instance()->clear_annual_to_zero($val['enter_date'],$start_day);
                    $need = 0;
                    $ten = Tools_Tools::get_instance()->clear_annual_to_zero($val['enter_date'],'2010-12-31 00:00:00');
                    if($sys['oneyear_leave_annual']) {
                        $need += $sys['oneyear_leave_annual'];
                    }
                    if($ten['oneyear_leave_annual']) {
                        $need += $ten['oneyear_leave_annual'];
                    }
                    $need = $need  - $clear_day - $twevle - $evlevent;
                    $te = 0;
                    $te = $sys['oneyear_leave_annual'] + $ten['oneyear_leave_annual'];

                    if($need < 0) {
                        $need = 0;
                    }
                    if(true) {
                        $update = $history + $leave_day + $evlevent + $twevle;
                        $total_annual = Tools_Tools::get_instance()->annual($val['enter_date']);
                        $update_sql = "REPLACE INTO user_info_ext(user_id,annual_used) VALUE({$val['user_id']},$update)";
                        //echo $update_sql,"+",$history,"+",$leave_day,"+",$excel_annual,"+",$evlevent,"+",$left_annual,"\n";
                        $left = $total_annual - $update;
                        //echo $val['name'],",",$val['code'],",",substr($val['enter_date'],0,10),",",$total_annual,",",$update,",",$left,",",$need,",",$tostop,",",$last_days,",",$last_base,",",$left_annual,",",$evlevent,",",$twevle,",",$leave_day,"\n";
                        $return = $this->execute($update_sql, array(),$this->writedb);
                        if($return) {
                            echo '更新成功！'."\n";
                        } else {
                            echo '更新失败'."\n";
                            $fail .= $val['Code'].',';
                        }
                    }
                }

            }
        }
    }

    /**
     * 每天更新计算到入职日期的员工年假，2009年12月30日年假
     * @param date $end_date
     * */
    public function import_history_used_annual_nine_file($end_date) {
        /** 组装常有数据 **/
        $q_sql = "SELECT user_id,annual,year FROM history_annual";
        $d = $this->get_db_rows($q_sql, $this->readdb ,array());
        if($d) {
            foreach ($d as $key => $val) {
                //$all[$val['user_id']] += $val['annual'];
                if($val['year'] == '2011') {
                    $all[$val['user_id']][0] = $val['annual'];
                } elseif ($val['year'] == '2012') {
                    $all[$val['user_id']][1] = $val['annual'];
                }
            }
        }
        $start = 0;
        echo "姓名,员工号,入职时间,总年假,已使用年假,剩余年假,截止2012-12-31要休年假,10-11年总年假,截止2009-12-31年假,2009年入职日到2009-12-31总天数,2009年入职日起年假基数,2009年入职日到2009-12-31年假天数,11年历史使用年假,12年历史使用年假,考勤系统登记年假\n";
        while(true){
            $sql = "SELECT user_id,code,enter_date,name FROM user_info WHERE enter_date != '0000-00-00 00:00:00' AND dimission_date = '0000-00-00 00:00:00' ORDER BY enter_date asc limit $start,100";
            $tmp = $this->get_db_rows($sql, $this->readdb, array());
            if(empty($tmp)) {
                break;
            }
            $start += 100;
            foreach ($tmp as $key => $val) {
                $totalday = 0;
                $enter = strtotime($val['enter_date']);
                $now = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $totalday = intval(ceil(($now - $enter)/86400));
                $year = intval($totalday/365);
                $subsql = "SELECT sum(leave_time) as leave_long FROM leave_record l where type = '年假' AND (status = '已批准' or status = '未审核') AND user_id = '{$val['user_id']}'";
                $leave = $this->get_db_row($subsql, $this->readdb, array());
                $leave_day = empty($leave['leave_long']) ? 0:$leave['leave_long'];
                $enterdate = strtotime($val['enter_date']);
                $now = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $year = intval($totalday/365);
                if($totalday > 365) {
                    $evlevent = 0;
                    $left_annual = 0;
                    $tostop = 0;
                    $twevle = 0;
                    $last_base = 0;
                    $last_days = 0;
                    $clear_day = 0;
                    $evlevent = isset($all[$val['user_id']]) ? $all[$val['user_id']][0]:0;
                    $work_total = Tools_Tools::get_instance()->clear_annual_to_zero($val['enter_date'],$end_date);
                    $twevle = isset($all[$val['user_id']]) ? $all[$val['user_id']][1]:0;
                    if(empty($work_total)) {
                        $history = 0;
                    } else {
                        $history = $work_total['annual'];
                        $tostop = $history;
                        $left_annual = $work_total['left_annual'];
                        $last_base = $work_total['last_base'];
                        $last_days = $work_total['last_day'];
                        $last_year_annual = $work_total['next_annual'];
                    }
                    apf_require_class('Bll_Attendance_LeaveRecord');
                    $l_bll = new Bll_Attendance_LeaveRecord();
                    $start_day = date('Y-m-d',mktime(0,0,0,1,0,date('Y')));
                    $end_day = date('Y-m-d',mktime(0,0,0,1,0,date('Y')+1));
                    //用户当年请假总数
                    $clear_day = $l_bll->get_annual_by_condition($val['user_id'],$start_day,$end_day);
                    //推算需要清零的假
                    $sys = Tools_Tools::get_instance()->clear_annual_to_zero($val['enter_date'],$start_day);
                    $need = 0;
                    $ten = Tools_Tools::get_instance()->clear_annual_to_zero($val['enter_date'],'2010-12-31 00:00:00');
                    if($sys['oneyear_leave_annual']) {
                        $need += $sys['oneyear_leave_annual'];
                    }
                    if($ten['oneyear_leave_annual']) {
                        $need += $ten['oneyear_leave_annual'];
                    }
                    $need = $need  - $clear_day - $twevle - $evlevent;
                    $te = 0;
                    $te = $sys['oneyear_leave_annual'] + $ten['oneyear_leave_annual'];

                    if($need < 0) {
                        $need = 0;
                    }

                    if(true) {
                        $update = $history + $leave_day + $evlevent + $twevle;
                        $total_annual = Tools_Tools::get_instance()->annual($val['enter_date']);
                        $update_sql = "REPLACE INTO user_info_ext(user_id,annual_used) VALUE({$val['user_id']},$update)";
                        //echo $update_sql,"+",$history,"+",$leave_day,"+",$excel_annual,"+",$evlevent,"+",$left_annual,"\n";
                        $left = $total_annual - $update;
                        echo $val['name'],",",$val['code'],",",substr($val['enter_date'],0,10),",",$total_annual,",",$update,",",$left,",",$need,",",$te,",",$tostop,",",$last_days,",",$last_base,",",$left_annual,",",$evlevent,",",$twevle,",",$leave_day,"\n";
                        /*$return = $this->execute($update_sql, array(),$this->writedb);
                        if($return) {
                            echo '更新成功！'."\n";
                        } else {
                            echo '更新失败'."\n";
                            $fail .= $val['Code'].',';
                        }*/
                    }
                }

            }
        }
    }

     /**
     * 把原公出为天的改为小时
     * @param int $end_time
     * @author coldarmy
     * **/
    private function convert_gongchu_leave_time($end_time) {
        if(empty($end_time)) {
            $end_time = '1345510800';
        }
        $start_time = '1341331200';
        $start = 0;
        //echo "姓名,员工号,入职时间,总年假,已使用年假,剩余年假,截止2012-12-31要休年假,截止2010-12-31年假,2010年入职日到2010-12-31总天数,2010年入职日起年假基数,2010年入职日到2010-12-31年假天数,11年历史使用年假,12年历史使用年假,考勤系统登记年假\n";
        while(true){
            $sql = "SELECT id,leave_time,user_id,start_time,end_time from leave_record where type = '公出' AND apply_time_ext >= $start_time AND apply_time_ext <= $end_time limit $start,100";
            $tmp = $this->get_db_rows($sql, $this->writedb, array());
            if(empty($tmp)) {
                break;
            }
            $start += 100;
            foreach ($tmp as $key => $val) {
                $st = strtotime($val['start_time']);
                $et = strtotime($val['end_time']);
                $cut_time = round(($et - $st)/3600);
                $this->log("ID:{$val['id']}原公出为{$val['start_time']} -- {$val['end_time']} 时长:{$val['leave_time']},改为小时后为:{$cut_time}");
                $u_sql = "UPDATE leave_record set leave_time = {$cut_time} WHERE id = {$val['id']}";
                //$this->log($u_sql);
                $this->execute($u_sql, array(),$this->writedb);
            }
        }
    }

}
